/** @odoo-module **/

import { Component, useState } from "@odoo/owl";
import { registry } from "@web/core/registry";
import { useService } from "@web/core/utils/hooks";

/**
 * 扫码报工客户端动作组件
 */
export class ProductionScanClientAction extends Component {
    setup() {
        this.notification = useService("notification");
        this.state = useState({
            isScanning: false,
            lastResult: null,
            scanHistory: []
        });
        
        // 设置全局回调函数，用于接收扫码结果
        window.handleProductionScanComplete = (result) => {
            this.handleScanComplete(result);
        };
    }
    
    async startScan() {
        console.log("Starting production scan from client action");
        this.state.isScanning = true;
        this.state.lastResult = null;
        
        // 检查是否是Android APP
        if (typeof window.AndroidBarcodeScanner !== 'undefined') {
            console.log("Using Android native scanner");
            try {
                window.AndroidBarcodeScanner.scanBarcode();
            } catch (error) {
                console.error("Android scanner error:", error);
                this.notification.add("启动原生扫码失败：" + error.message, { type: "danger" });
                this.state.isScanning = false;
            }
        } else {
            // 使用HTML5扫描器
            console.log("Using HTML5 scanner");
            if (window.openProductionBarcodeScannerDirect) {
                try {
                    await window.openProductionBarcodeScannerDirect(null, null);
                    // HTML5扫描器关闭后重置状态
                    this.state.isScanning = false;
                } catch (error) {
                    console.error("HTML5 scanner error:", error);
                    this.notification.add("启动扫描器失败：" + error.message, { type: "danger" });
                    this.state.isScanning = false;
                }
            } else {
                this.notification.add("扫描器未加载，请刷新页面重试", { type: "warning" });
                this.state.isScanning = false;
            }
        }
    }
    
    handleScanComplete(result) {
        console.log("Scan complete callback:", result);
        this.state.isScanning = false;
        this.state.lastResult = result;
        
        // 添加到历史记录
        this.state.scanHistory.unshift({
            time: new Date().toLocaleTimeString('zh-CN'),
            success: result.success,
            message: result.message,
            traceid: result.work_order_traceid || '-'
        });
        
        // 只保留最近10条
        if (this.state.scanHistory.length > 10) {
            this.state.scanHistory = this.state.scanHistory.slice(0, 10);
        }
    }
}

ProductionScanClientAction.template = "production_planning.ScanClientAction";

// 注册客户端动作
registry.category("actions").add("production_scan_client_action", ProductionScanClientAction);

